from flask import Flask, request, jsonify
import time
import mysql.connector

app = Flask(__name__)

# 数据库连接配置
db_config = {
    "host": "localhost",  # MySQL服务器地址
    "user": "remote_user",  # 用户名
    "password": "ZZZxxx66!",  # 密码
    "database": "experiencelife"  # 数据库名称
}

def get_db_connection():
    return mysql.connector.connect(**db_config)

@app.route('/remotelogin', methods=['POST'])
def user_login():
    data = request.get_json()
    id_login = data['id']
    password_login = data['password']
    try:
        connection = get_db_connection()
        cursor = connection.cursor(dictionary=True)
        query = "SELECT * FROM remoteuser WHERE id = %s AND password = %s"
        cursor.execute(query, (id_login, password_login))
        user = cursor.fetchall()
        if not user:
            return jsonify({"message": "Id or password mistake!"}), 201
        else:
            return jsonify(user), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        cursor.close()
        connection.close()

@app.route('/remoteuser', methods=['POST'])
def add_user():
    """添加新用户"""
    data = request.get_json()
    if not data or 'name' not in data or 'password' not in data:
        return jsonify({"error": "Missing required fields"}), 400
    
    name = data['name']
    ip = data['ip']
    password=data['password']
    photo=data['photo']
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        cursor.execute("INSERT INTO remoteuser (name,password,ip,experience,level,immortalclass,photo) VALUES (%s,%s,%s,0,0,1,%s)", (name,password, ip,photo))
        connection.commit()
        return jsonify({"id": cursor.lastrowid}), 201
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        cursor.close()
        connection.close()

@app.route('/chat', methods=['POST'])
def add_chat_message():
    data = request.get_json()
    id_from = data['id']
    id_to=data['idfrom']
    chat_message = data['chatmessage']  # Corrected variable name
    timew = int(time.time())

    try:
        connection = get_db_connection()  # Ensure this function is defined elsewhere in your code
        cursor = connection.cursor()
        
        # Randomly select a user with level > 0
        if id_to<0:
            cursor.execute("SELECT id FROM remoteuser WHERE level > 0 ORDER BY RAND() LIMIT 1")
            result = cursor.fetchone()
            if not result:  # Check if there is no valid user found
                return jsonify({"error": "No suitable user found"}), 404
            id_to = result[0]
        # Insert the chat message into the database
        cursor.execute("INSERT INTO chatmessage (id_from,id_to,timew,message_text) VALUES (%s,%s,%s,%s)", 
                       (id_from, id_to, timew, chat_message))
        connection.commit()
        return jsonify({"id": cursor.lastrowid}), 201
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        cursor.close()
        connection.close()

@app.route('/saveexperience', methods=['POST'])
def save_experience():
    data = request.get_json()
    id = data['id']
    experience = data['experience']
    level=data['level']
    immortalclass=data['immortalclass']
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        sql_update_query ="""UPDATE remoteuser SET experience = %s, level = %s,immortalclass=%s WHERE id = %s"""
        input_data = (experience, level, immortalclass, id,)
        timew=int(time.time())-1800
        cursor.execute(sql_update_query, input_data)
        query = "SELECT * FROM chatmessage WHERE id_to = %s AND timew > %s"
        cursor.execute(query, (id,timew,))
        receivedm = cursor.fetchall()
        delete_query = "DELETE FROM chatmessage WHERE id_to = %s"
        cursor.execute(delete_query, (id,))
        connection.commit()
        if not receivedm:
            return jsonify({"message": "nomessage"}), 201
        else:
            return jsonify(receivedm), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        cursor.close()
        connection.close()

@app.route('/savelinggen', methods=['POST'])
def save_linggen():
    data = request.get_json()
    id = data['id']
    linggen = data['linggen']
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        sql_update_query ="""UPDATE remoteuser SET linggen = %s WHERE id = %s"""
        input_data = (linggen, id,)
        cursor.execute(sql_update_query, input_data) 
        connection.commit()
        if not receivedm:
            return jsonify({"message": "nomessage"}), 201
        else:
            return jsonify(receivedm), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        cursor.close()
        connection.close()

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')  # 监听所有网络接口
